#! /usr/bin/env python3
# -*- coding:utf-8 -*-

import sys
import os
import getopt
import configparser
import param_cache
import unit_strategy
import unit_shell_strategy
import unit_serial_strategy
import unit_coap_strategy
import unit_request_strategy


strategy = {'shell': unit_strategy.UnitContext(unit_shell_strategy.UnitShellProcess()),
            'serial': unit_strategy.UnitContext(unit_serial_strategy.UnitSerialProcess()),
            'coap': unit_strategy.UnitContext(unit_coap_strategy.UnitCoapProcess()),
            'request': unit_strategy.UnitContext(unit_request_strategy.UnitRequestProcess())}


def test():
    global_conf = configparser.ConfigParser()
    unit_conf = configparser.ConfigParser()
    global_conf.read('./config.ini')
    unit_conf.read('./test01.ini')

    unit_list = sorted(unit_conf.items(), key=lambda x: x[0])
    unit_list = list(filter(lambda x: x[0] != 'DEFAULT', unit_list))

    p1 = param_cache.ParamCache(global_conf, unit_list)

    while True:
        p1 = p1.push_config()

        if p1.get_param_protocol() in strategy:
            unit = strategy[p1.get_param_protocol()]
            unit.process(p1)
        if p1.config_count() == 0:
            break


def process(global_path, unit_path):
    global_conf = configparser.ConfigParser()
    unit_conf = configparser.ConfigParser()
    global_conf.read(global_path)
    unit_conf.read(unit_path)

    unit_list = sorted(unit_conf.items(), key=lambda x: x[0])
    unit_list = list(filter(lambda x: x[0] != 'DEFAULT', unit_list))

    p1 = param_cache.ParamCache(global_conf, unit_list)

    while True:
        p1 = p1.push_config()

        if p1.get_param_protocol() in strategy:
            unit = strategy[p1.get_param_protocol()]
            unit.process(p1)
        if p1.config_count() == 0:
            break


def usage():
    print('''
        This is the port of test system and is not recommended for use alone
        usage : unit.py -g [global_config] -c [config] -p [path]
    ''')


if __name__ == '__main__':
    if len(sys.argv) == 1:
        test()
        sys.exit()

    opts, args = getopt.getopt(sys.argv[1:], "htg:c:p:")
    config_path = ""
    for op, value in opts:
        if op == '-g':
            global_config = value
        elif op == '-c':
            config = value
        elif op == '-p':
            config_path = value
        elif op == '-h':
            usage()
            sys.exit()
        elif op == '-t':
            test()
            sys.exit()

    global_config = os.path.join(config_path, global_config)
    config = os.path.join(config_path, config)
    process(global_config, config)
